// pages/xiangqing/xiangqing.js
import config from '../../mars/conf/config'
import * as echarts from '../../ec-canvas/echarts'
var charts = require('../../mars/modules/charts')
var hiway = require('../../mars/modules/mars')
const { xiangqing,shujutongji, scanCodeBangding,homefenxiang,fenxiangjilu,unbind,reset} = require("../../util/api")

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });



  canvas.setChart(chart);

  var option = {
    tooltip: {
      // trigger: 'item'
    },
    legend: {
      top:20,
      left: 'center',
      z: -1
    },
    series: [  {
      type: 'pie',
      radius: '50%',
      label: {
        normal: {
          position: 'inside', 
          show: true,
          // formatter:app.globalData.type==1? '{c}'+'L': '{c}'+'天'
          formatter:function(params) {
           
            if(app.globalData.type==1){
              return params.name+params.value+'L'
            }else{
              return params.name+params.value+'天'
            }
        
          }
        }
      },

      data: [
        { value: null, name: '已用',color:'red' },
        { value: null, name: '剩余' },
      ],
    }]
  };
  setTimeout(function() {
    console.log('从这里取app里的数据',app.globalData.type)
    if(app.globalData.type==1){
      option.series[0].data[0].value = app.globalData.yiyong.toFixed(2);
      option.series[0].data[1].value = app.globalData.shengyu.toFixed(2);
    }else{
      option.series[0].data[0].value = app.globalData.yiyong.toFixed(0);
      option.series[0].data[1].value = app.globalData.shengyu.toFixed(0);
    }
   
    chart.setOption(option, true);
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 168,
      height: 168,
      canvasId: 'Canvas',
      success: (res) => {
        console.log('canvasImg',res)
      }
    });
  
  }, 1500)

  return chart;
  
}

//  function initBarChart(canvas, width, height, dpr) {
//   const chart = echarts.init(canvas, null, {
//     width: width,
//     height: height,
//     devicePixelRatio: dpr // 像素
//   });
//   canvas.setChart(chart);
//    let 
//    option = {
//     grid: {
//       left: '3%',
//       right: '4%',
//       bottom: '3%',
//       containLabel: true
//     },
//     dataZoom: [
//       {
//         type: 'inside',
//         start: 0,
//         end: 20
//       },
//       {
//         start: 0,
//         end: 20
//       }
//     ],
//      xAxis: {
//        type: 'category',
//        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
//      },
//      yAxis: {
//        type: 'value'
//      },
//      series: [
//        {
//          data: [150, 230, 224, 218, 135, 147, 260],
//          type: 'line'
//        }
//      ]
//    };
//   chart.setOption(option);
//   return chart;
// }

var app = getApp()
Page({
  data: {
    length:'',
    nowdate:'',
    datelist:[],
    yiyong:200,
    shengyu:300,
    pieImg:'',
    ec: {
      onInit: initChart,
     
    },
    ecLine: {
     
      lazyLoad: true 
    },
    lvxinCode:'',
    showro:false,
    list:[],
    deviceH: 0,
    deviceW: 0,
    index:0,
    eqId:"",
    phone:"",
    eqCode:"",
    currentTab:"2",
    xiangqing:{},
    heqId:"",
    recordId:"",
    renewList:[],
    streetlinechartec: {
      lazyLoad: true,
      img:"",
    },
    type:0,
    sharersid:0,
    counts:[10],
    dates:["10"],
    canvasImg:'',
   lvxinId:'',
   start:'',
   end:'',
   startyue:"",
   endyue:'',
   startyear:'',
   endyear:'',
   dataShow:''
  },

  //初始化图表
  init_echarts: function () {
    this.linechart.init((canvas, width, height) => {
      // 初始化图表
      const Chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });

      Chart.setOption(this.getOption());
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return Chart;
    });
  },


  

  getOption() {
    // let base = +new Date(1988, 9, 3);
    // let oneDay = 24 * 3600 * 1000;
    // let data = [[base, Math.random() * 300]];
    // for (let i = 1; i < 20000; i++) {
    //   let now = new Date((base += oneDay));
    //   data.push([+now, Math.round((Math.random() - 0.5) * 20 + data[i - 1][1])]);
    // }
  var  option = {
      xAxis: {
        data:this.data.dates
      },
      yAxis: {
        type: 'value',
       
      },
      dataZoom: [
        {
          type: 'inside',
          start: 0,
          end: 20
        },
        {
          start: 0,
          end: 20
        }
      ],
      series: [
        {
        
          type: 'line',
          smooth: true,
          data: this.data.counts
        }
      ]
    };
    return option

 },



  scannum(e){
    let that=this
    wx.scanCode({
      success (res) {
        that.setData({
        lvxinCode:res.result
       })
      }
    })
  },

  noresetro(){
    this.setData({
      showro:false
    })
    this.hideModal()
  },
  lvxincode(e){
    this.setData({
      lvxinCode:e.detail.value
    })
  },
  resetRo(e){
    console.log(e)
    let lvxinid=e.currentTarget.dataset.lvid
    let that=this
    wx.showModal({
      title: '提示',
      content: '确定复位吗？',
      success (res) {
        if (res.confirm) {

          let p={
            id:that.data.eqId,
            lvxinId:lvxinid,
          }
          reset(p).then(res=>{
            if(res.code==200){
              wx.showToast({
                title: '复位成功',
                icon: 'success',
                duration: 2000
              })
              setTimeout(() =>{
                that.hideModal()
                that.onShow()
              },2000)
             
            } else{
              wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
            
          })
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

   
   
  },
  unbinding(e){
    let that=this
    wx.showModal({
      title: '提示',
      content: '确定解绑吗？',
      success (res) {
        if (res.confirm) {
         let p={
           memberId:wx.getStorageSync('memberId'),
           eqCode:that.data.eqCode,
           recordId:that.data.recordId
         }

         unbind(p).then(res=>{
           if(res.code==200){
            wx.navigateBack({
              delta: 1
            })
           }
         })
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    
  },

  //月统计
  yuetongji(e){
    this.setData({
      currentTab:e.currentTarget.dataset.currenttab,
      type:1,
   
    })
    this.e_charts()
  },

  //日统计
  ritongji(e){
    this.setData({
      currentTab:e.currentTarget.dataset.currenttab,
      type:0,
    })
    this.e_charts()
 
  },


  // 年统计
  niantongji(e){
    this.setData({
      currentTab:e.currentTarget.dataset.currenttab,
      type:2,
    })
    this.e_charts()
  },

  //日统计选择开始时间
  starttime(e){
    this.setData({
      start:e.detail.value
    })
  },

  //月统计选择开始时间
  starttimeyue(e){
    this.setData({
      startyue:e.detail.value
    })
  },
  //年统计选择开始时间
  starttimeyear(e){
    this.setData({
      startyear:e.detail.value
    })
  },
  //年统计选择结束时间
  endtimeyear(e){
      this.setData({
        endyear:e.detail.value
      })
  },
  //日统计选择结束时间
  endtime(e){
    this.setData({
      end:e.detail.value
    })
  },

  //月统计选择结束时间
  endtimeyue(e){
    this.setData({
      endyue:e.detail.value
    })
  },

  //日统计查询
  selcettime(){
    if(this.data.start==''){
      wx.showToast({
        title: '请选择开始时间',
        icon: 'none',
        duration: 1000
      })
      return
    }
    if(this.data.end==''){
      wx.showToast({
        title: '请选择结束时间',
        icon: 'none',
        duration: 1000
      })
      return
    }
    this.e_charts()
  },
  //月统计查询
  selcettimeyue(){
    if(this.data.startyue==''){
      wx.showToast({
        title: '请选择开始时间',
        icon: 'none',
        duration: 1000
      })
      return
    }
    if(this.data.endyue==''){
      wx.showToast({
        title: '请选择结束时间',
        icon: 'none',
        duration: 1000
      })
      return
    }
    this.e_charts()
  },
  //年统计查询
  selcettimeyear(){
    if(this.data.startyear==''){
      wx.showToast({
        title: '请选择开始时间',
        icon: 'none',
        duration: 1000
      })
      return
    }
    if(this.data.endyear==''){
      wx.showToast({
        title: '请选择结束时间',
        icon: 'none',
        duration: 1000
      })
      return
    }

    this.e_charts()

  },

  peiwang(){
    wx.navigateTo({
      url: '/pages/shouye/peiwang/peiwang',
    })
  },
  baoxiu(){
    wx.navigateTo({
      url: '/pages/addbaoxiu/addbaoxiu?heqId='+this.data.heqId,
    })
  },
  xufei(){
    console.log('123123', this.data)
    wx.navigateTo({
      url: '/pages/xufei/xufei?heqId='+this.data.heqId+'&recordId='+this.data.recordId+'&etId='+this.data.etId+'&eqId='+this.data.eqId,
    })
  },

  //点击分享按钮
  fenxiang(){
    this.setData({
      show:true,
      phone:'',
      inputFocus:true

    })
    this.showModal();
  },
  input(e){
    this.setData({
    phone:e.detail.value
    })
  },
  // 点击让输入框获取焦点
tapInput() {
  this.setData({
    inputFocus: true,
  });
},

// 输入框获取焦点
getfocus(){
  console.log('输入框获取了焦点')
},
inputFocus(){
  this.setData({
    phone:''
  });
},
blurinput(e) {
  this.setData({
    phone: e.detail.value
  });
},
  tel(){
    if(this.data.phone.length!=11){
      wx.showToast({
        title: '手机号不正确',
        icon: 'error',
        duration: 2000
      })
    }else{
      let p={
        memberId:wx.getStorageSync('memberId'),
        phone:this.data.phone,
        eqCode:this.data.eqCode,
        recordId:this.data.recordId

      }
      console.log(p)
      homefenxiang(p).then(res=>{
        console.log(res)
        if(res.code==200){

          this.setData({
            show:false
          })
          this.hideModal()
          wx.showToast({
            title: '分享成功',
            icon: 'success',
            duration: 2000
          })
          

        }else{
          wx.showToast({
            title: res.msg,
            icon: 'error',
            duration: 2000
          })
          console.log(res)
        }
       
      })

     
    }
   
  },
  quxiao(){
    this.setData({
      show:false

    })
   this.hideModal()
  },
  
  showModal: function () {
    // 显示遮罩层
     var animation= wx.createAnimation({
       duration: 200,
       timingFunction: "linear",
       delay: 0
     })
     this.animation = animation
     animation.translateY(300).step()
     this.setData({
       animationData: animation.export(),
       showModalStatus: true
     })
     setTimeout(function () {
       animation.translateY(0).step()
       this.setData({
         animationData: animation.export()
       })
     }.bind(this), 200)
   },
   hideModal() {
   
this.setData({
  showModalStatus:false,
  show:false
})
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.linechart=this.selectComponent('#mychart')
  
   if(options.type == 1)
   {
    this.setData({
      etId:options.etid,
      eqId:options.eqId,
      type:options.type,
      heqId:options.heqId,
      eqCode:options.eqCode,
      recordId:options.recordId,
      sharersid:options.sharersid
     })
     if(wx.getStorageSync('memberId') == null)
     {
       wx.navigateTo({
         url: '/pages/denglu/denglu',
       })
     }
   }
   else
   {
    this.setData({
       etId:options.etid,
      eqId:options.eqId,
      type:options.type,
      heqId:options.heqId,
      eqCode:options.eqCode
     }) 
   }
  },
  //初始化图表
  initGraph: function () {
  
    let params = {}
    params.canvas_id = 'lineGraph'
    params.ytitle = '用水量（升）'
    params.xcate = this.data.dates
    params.data = [{
        name: '出水量',
        data: this.data.counts,
     }
  ]
     params.width = this.data.deviceW
     params.height = 410
    charts.shapeLine(params)
    setTimeout(() => {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        canvasId: 'lineGraph',
        success: (res) => {
        console.log(res,'0000')
          this.setData({ canvasImg: res.tempFilePath });
        }
      });
    },1000);

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
   
  },
  //获取当前日期 在选择器的时候要用
   getdate(){
    var myDate = new Date();
    let Y =myDate.getFullYear();
    var M = myDate.getMonth()+1;
   var D =  myDate.getDate();
  if(M < 10&&D < 10){
   this.setData({
    nowdate:Y+"-0"+M+"-0"+D,
   })
  }else if( D < 10){
    this.setData({
      nowdate:Y+"-"+M+"-0"+D,
     })
  }else if(M<10){
    this.setData({
      nowdate:Y+"-0"+M+"-"+D,
     })    
  }
   this.setData({
     nowyear:Y
   })
 
  
   },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  
    //获取当前日期
      this.getdate()
     let _this = this
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          deviceH: res.windowHeight,
          deviceW: res.windowWidth,
        })
      }
    })
   if(this.data.type == 1)
   {
    let par={
      memberId:wx.getStorageSync('memberId'),
      eqCode:this.data.eqCode,
      recordId:this.data.recordId, 
      type:this.data.type,
      sharersid:this.data.sharersid
  }
    scanCodeBangding(par).then(res=>{
      _this.e_charts()
      })
   }
   else
   {
    this.e_charts()
   }  
  },
//折线图生成
  e_charts()
  {
        let par={
          eqId:this.data.eqId, 
        }
      xiangqing(par).then(res=>{
      
       app.globalData.yiyong = res.data.leaseList[0].zongliulianghetianshu-res.data.leaseList[0].shengyuliulianghetianshu
      app.globalData.shengyu = res.data.leaseList[0].shengyuliulianghetianshu
    app.globalData.type=res.data.taocanType
    console.log(res,'取数据并且存到app里')
          let arr=[];
          arr= res.data.etImgs.split(",")
          res.data.arr=arr;
          this.setData({
            length:res.data.renewList.length-1,
            xiangqing:res.data,
            recordId:res.data.recordId,
            renewList:res.data.renewList,
            dataShow:res.data.dataShow ,
          })
       
       })
      
       //如果选中的是月统计
  if(this.data.currentTab==1){
    let p={
      eqId:this.data.heqId,
      type:this.data.type,
      memberId:wx.getStorageSync('memberId'),
      startTime:this.data.startyue,
      endTime:this.data.endyue
    }
    shujutongji(p).then(res=>{
     
      this.setData({
        counts:res.data.counts,
        dates:res.data.dates,
        datelist:res.data.res
      })
      if(this.data.dataShow==0){
     
        this.init_echarts()
      }
    })

    //如果选中的是日统计
  }else if(this.data.currentTab==2){
    let p={
      eqId:this.data.heqId,
      type:this.data.type,
      memberId:wx.getStorageSync('memberId'),
      startTime:this.data.start,
      endTime:this.data.end
    }
    shujutongji(p).then(res=>{
 
      this.setData({
        counts:res.data.counts,
        dates:res.data.dates,
        datelist:res.data.res
      })
      if(this.data.dataShow==0){
      
        this.init_echarts()
      }
      
    })
  }else{
    //选中的是年统计
    if(this.data.endyear==this.data.nowyear){
      console.log(this.data.nowdate)
      console.log('为今年')
      let p={
        eqId:this.data.heqId,
        type:this.data.type,
        memberId:wx.getStorageSync('memberId'),
        startTime:this.data.startyear+'-01-01',
        endTime:this.data.nowdate
      }
      shujutongji(p).then(res=>{
        console.log(res)
        this.setData({
          counts:res.data.counts,
          dates:res.data.dates,
          datelist:res.data.res
        })
        if(this.data.dataShow==0){
          this.init_echarts()
        }
      })
    }else if(this.data.startyear==''||this.data.endyear==''){
      console.log('为空')
      let p={
        eqId:this.data.heqId,
        type:this.data.type,
        memberId:wx.getStorageSync('memberId'),
        startTime:this.data.startyear,
        endTime:this.data.endyear
      }
      shujutongji(p).then(res=>{
        console.log(res)
        this.setData({
          counts:res.data.counts,
          dates:res.data.dates,
          datelist:res.data.res
        })
        if(this.data.dataShow==0){
          this.init_echarts()
        }
      })
    }else{
      console.log('为别的年')
      let p={
        eqId:this.data.heqId,
        type:this.data.type,
        memberId:wx.getStorageSync('memberId'),
        startTime:this.data.startyear+'-01-01',
        endTime:this.data.endyear+'-12-31'
      }
      shujutongji(p).then(res=>{
        console.log(res)
        this.setData({
          counts:res.data.counts,
          dates:res.data.dates,
          datelist:res.data.res
        })
        if(this.data.dataShow==0){
          this.init_echarts()
        }
      })
    }
   
   
  }
  
      // let m={
      //   memberId:wx.getStorageSync('memberId'),
      //   eqId:this.data.heqId
      // }
      
      // fenxiangjilu(m).then(res=>{
      //   this.setData({
      //     list:res.data
      //   })
        
      // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
   
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
   this.onShow()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(res) {
  //   if (res.from === 'button') {
  //     console.log(this.data)
  //     return {
  //       title: '家用净水机-租用设备',
  //       path: '/pages/xiangqing/xiangqing?eqId='+this.data.eqId  + "&etid=" + this.data.etId + "&eqCode=" + this.data.xiangqing.eqCode + "&recordId=" + this.data.recordId + "&sharersid=" + wx.getStorageSync('memberId') + "&heqId=" + this.data.heqId + "&type=1"
  //     }
     
  //   }else{
  //     return {
  //       title: '家用净水机',
  //       path: '/pages/shouye/shouye',
  //     }
  
  //   }
   },

})